<template>
  <div>
    <el-dialog :visible.sync="dialogFormVisible" :title="title">
      <el-form :model="chapter">
        <el-form-item :label-width="formLabelWidth" label="章节标题">
          <el-input v-model="chapter.title" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="章节排序">
          <el-input-number v-model="chapter.sort" :min="0" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdateChapter">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import courseApi from '@/api/course'
export default {
  data() {
    return {
      chapter: {
        sort: 0
      },
      title: '添加章节',
      dialogFormVisible: false,
      formLabelWidth: '80px'
    }
  },
  methods: {
    // 编辑章，回显章数据，并显示对话框方法
    open(id) {
      courseApi.get(id).then(r => {
        this.chapter = r.data.item
        this.title = '更新章节'
        this.dialogFormVisible = true
      })
    },
    // 新增或更新章节信息
    saveOrUpdateChapter() {
      if (this.chapter.id) {
      //  更新
        this.update()
      } else {
      // 新增
        this.save()
      }
    },
    update() {
      courseApi.update(this.chapter).then(r => {
        this.$message.success('新增成功')
        this.chapter = {
          sort: 0
        }
        this.dialogFormVisible = false
        this.$parent.listNestedChapters()
      })
    },
    save() {
      // 绑定当前章属于哪个课程
      this.chapter.courseId = this.$parent.$parent.courseId
      courseApi.saveChapter(this.chapter).then(r => {
        this.$message.success('新增成功')
        this.chapter = {
          sort: 0
        }
        this.dialogFormVisible = false
        this.$parent.listNestedChapters()
      })
    }
  }
}
</script>

